package com.quectel.grid.controller.household;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.lang.func.LambdaUtil;
import cn.hutool.core.util.DesensitizedUtil;
import com.quectel.business.common.grid.GridMemberBindResourcesBusiness;
import com.quectel.constant.core.grid.GridConstant;
import com.quectel.constant.core.household.HouseholdConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.module.grid.dto.GridBindingDto;
import com.quectel.core.module.grid.dto.GridDto;
import com.quectel.core.module.grid.dto.GridMemberDto;
import com.quectel.core.module.grid.service.GridBindingService;
import com.quectel.core.module.grid.service.GridService;
import com.quectel.core.module.household.dto.HouseholdDto;
import com.quectel.core.module.household.dto.HouseholdRelationsDto;
import com.quectel.core.module.household.dto.HouseholdRoomDto;
import com.quectel.core.module.household.service.HouseholdFamilyService;
import com.quectel.core.module.household.service.HouseholdRoomService;
import com.quectel.core.module.household.service.HouseholdService;
import com.quectel.core.module.household.service.HouseholdSocialRelationsService;
import com.quectel.core.module.village.dto.VillageRoomDto;
import com.quectel.core.module.village.service.VillageRoomService;
import com.quectel.grid.controller.BaseController;
import com.quectel.grid.interceptor.LoginGridMemberSession;
import com.quectel.grid.util.SessionHolder;
import com.quectel.grid.vo.household.HouseholdAndRoomSaveVo;
import com.quectel.grid.vo.household.HouseholdResp;
import com.quectel.util.common.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 在这里编写说明
 *
 * @author: bob
 * @email: bob.yu@quectel.com
 * @date: 2023-02-15 14:45:00
 */
@RestController
@RequestMapping("household")
@Tag(name = "HouseholdController", description = "实有人口相关的api")
public class HouseholdController extends BaseController {


    @DubboReference
    private HouseholdService householdService;
    @DubboReference
    private HouseholdRoomService householdRoomService;
    @DubboReference
    private GridService gridService;
    @DubboReference
    private GridBindingService gridBindingService;
    @DubboReference
    private VillageRoomService villageRoomService;
    @DubboReference
    private HouseholdSocialRelationsService householdSocialRelationsService;
    @DubboReference
    private HouseholdFamilyService householdFamilyService;

    @Autowired
    private GridMemberBindResourcesBusiness gridMemberBindResourcesBusiness;


    /**
     * 查询住户家庭或者社会关系列表
     */
    @GetMapping("queryHouseholdRelation")
    @Operation(summary = "查询住户家庭或者社会关系列表")
    public Response<HouseholdRelationsDto> queryHouseholdRelation(
            @Parameter(description = "住户ID") @RequestParam Long householdId,
            @Parameter(description = "全部0家庭1社会2") @RequestParam String queryFlag
    ) {
        HouseholdDto householdDto = householdService.selectCacheById(householdId);
        Boolean hasPermission = gridMemberBindResourcesBusiness.checkGridMemberHouseholdResource(SessionHolder.getGridMember().getTenantId(), SessionHolder.getGridMember().getId(), householdDto.getId());
        if (Boolean.FALSE.equals(hasPermission)) {
            return Response.error("住户不存在");
        }
        HouseholdRelationsDto householdRelationsDto = new HouseholdRelationsDto();
        householdRelationsDto.setHouseholdId(householdId);

        if (HouseholdConstants.RELATION_RANGE_FLAG_ALL.equals(queryFlag) || HouseholdConstants.RELATION_RANGE_FLAG_FAMILY.equals(queryFlag)) {
            //家庭关系
            householdRelationsDto.setHouseholdFamilyList(householdFamilyService.queryByHouseholdId(householdId));
        }

        if (HouseholdConstants.RELATION_RANGE_FLAG_ALL.equals(queryFlag) || HouseholdConstants.RELATION_RANGE_FLAG_SOCIAL.equals(queryFlag)) {
            //社会关系
            householdRelationsDto.setSocialRelationsList(householdSocialRelationsService.queryByHouseholdId(householdId));
        }

        return Response.<HouseholdRelationsDto>ok().wrap(householdRelationsDto);
    }


    @PostMapping("update")
    @Operation(summary = "人口登记更新")
    public Response<Object> update(@RequestBody @Validated HouseholdAndRoomSaveVo saveVo) {
        LoginGridMemberSession loginGridUserSession = SessionHolder.getLoginGridUserSession();
        GridMemberDto gridMember = loginGridUserSession.getGridMember();

        HouseholdAndRoomSaveVo.HouseholdVo householdVo = saveVo.getHouseholdVo();
        if (householdVo.getId() == null) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        HouseholdDto household = householdService.selectById(householdVo.getId());

        // 更新household
        HouseholdDto householdDto = CopyUtils.copyObj(householdVo, HouseholdDto.class);
        householdDto.setTenantId(household.getTenantId());
        householdDto.setVillageId(household.getVillageId());
        householdDto.setEditor(gridMember.getName());
        householdDto.setEditTime(new Date());
        List<HouseholdAndRoomSaveVo.HouseholdRoomVo> roomList = saveVo.getRoomList();

        List<HouseholdRoomDto> roomDtos = new ArrayList<>();
        for (HouseholdAndRoomSaveVo.HouseholdRoomVo householdRoomVo : roomList) {
            HouseholdRoomDto householdRoomDto = new HouseholdRoomDto();
            householdRoomDto.setHouseholdId(householdDto.getId());
            householdRoomDto.setVillageId(householdDto.getVillageId());
            householdRoomDto.setRoomId(householdRoomVo.getRoomId());
            householdRoomDto.setIdentityCategory(householdRoomVo.getIdentityCategory());
            roomDtos.add(householdRoomDto);
        }

        householdDto.setHouseholdRoomDtoList(roomDtos);
        householdService.saveOrUpdateHouseholdAndRoom(householdDto);

        return Response.ok().wrap("信息更新成功");
    }


    @GetMapping("queryHouseholdListByRoomId")
    @Operation(summary = "通过房屋id查询住户信息")
    public Response<List<HouseholdResp>> queryHouseholdListByRoomId(
            @Parameter(description = "房屋id") @RequestParam Long roomId) {
        LoginGridMemberSession loginGridUserSession = SessionHolder.getLoginGridUserSession();

        List<HouseholdResp> result = new ArrayList<>();
        List<HouseholdRoomDto> householdRoomDtos = householdRoomService.selectByRoomId(roomId);
        if (CollectionUtils.isNotEmpty(householdRoomDtos)) {
            for (HouseholdRoomDto householdRoom : householdRoomDtos) {
                HouseholdDto householdDto = householdService.selectById(householdRoom.getHouseholdId());

                HouseholdResp householdResp = CopyUtils.copyObj(householdDto, HouseholdResp.class);
                VillageRoomDto villageRoom = villageRoomService.selectById(householdRoom.getRoomId());
                GridBindingDto gridBinding = gridBindingService.selectOne(GridConstant.SourceType.BUILDING.getType(), villageRoom.getBuildingId());
                if (gridBinding != null) {
                    Long gridId = gridBinding.getGridId();
                    GridDto grid = gridService.selectById(gridId);
                    if (grid != null) {
                        householdResp.setGridName(grid.getName());
                    }
                }
                if (householdDto != null) {
                    householdResp.setIdentityCategory(householdRoom.getIdentityCategory());
                    result.add(householdResp);
                }
            }
        }
        return Response.<List<HouseholdResp>>ok().wrap(result);
    }


    /**
     * 人口登记
     * 人员+居住信息 合并一次调用接口
     * 人员必需要绑定到楼栋,否则网格管理员看不到
     */
    @PostMapping("saveHousehold")
    @Operation(summary = "人口登记接口")
    public Response<Object> saveHousehold(@RequestBody @Validated HouseholdAndRoomSaveVo saveVo) {
        LoginGridMemberSession loginGridUserSession = SessionHolder.getLoginGridUserSession();
        GridMemberDto gridMember = loginGridUserSession.getGridMember();

        HouseholdAndRoomSaveVo.HouseholdVo householdVo = saveVo.getHouseholdVo();
        // 校验住户是否存在
        String mobile = householdVo.getMobile();

        List<HouseholdAndRoomSaveVo.HouseholdRoomVo> roomList = saveVo.getRoomList();
        if (CollectionUtils.isEmpty(roomList)) {
            return Response.error("网格添加住户必须绑定房屋信息");
        }

        // 校验
        for (HouseholdAndRoomSaveVo.HouseholdRoomVo roomVo : roomList) {
            GridDto gridDto = gridService.selectCacheById(roomVo.getGridId());
            HouseholdDto householdDto = householdService.selectByVillageIdAndMobile(gridDto.getVillageId(), mobile);
            if (householdDto != null) {
                return Response.error("住户手机号已存在");
            }
        }

        HouseholdDto householdAddly = CopyUtils.copyObj(householdVo, HouseholdDto.class);
        // save
        for (HouseholdAndRoomSaveVo.HouseholdRoomVo roomVo : roomList) {
            GridDto gridDto = gridService.selectCacheById(roomVo.getGridId());
            householdAddly.setTenantId(gridDto.getTenantId());
            householdAddly.setVillageId(gridDto.getVillageId());
            householdAddly.setCreator(gridMember.getName());
            householdAddly.setCreateTime(new Date());
            if (StringUtils.isEmpty(householdAddly.getTags())) {
                householdAddly.setTags("{}");
            }
            if (StringUtils.isEmpty(householdAddly.getCardImg())) {
                householdAddly.setCardImg(JacksonUtils.toJsonString(new ArrayList<>()));
            }
            Long householdId = householdService.save(householdAddly);
            // 住户房屋信息操作

            Long roomId = roomVo.getRoomId();
            HouseholdRoomDto householdRoomDto = householdRoomService.selectByHouseholdIdAndRoomId(householdId, roomId);
            if (householdRoomDto == null) {
                VillageRoomDto villageRoomDto = villageRoomService.selectCacheById(roomId);
                if (villageRoomDto != null) {
                    // 未查询到关联关系，保存关系
                    HouseholdRoomDto addly = new HouseholdRoomDto();
                    addly.setHouseholdId(householdId);
                    addly.setVillageId(villageRoomDto.getVillageId());
                    addly.setRoomId(roomId);
                    addly.setIdentityCategory(roomVo.getIdentityCategory());
                    householdRoomService.save(addly);
                }
            }
        }
        return Response.ok().wrap("信息录入成功");
    }


    /**
     * 信息
     */
    @GetMapping("info/{id}")
    @Operation(summary = "查询单条记录")
    public Response<HouseholdDto> info(@PathVariable("id") Long id) {
        LoginGridMemberSession loginGridUserSession = SessionHolder.getLoginGridUserSession();
        Map<String, Object> params = new HashMap<>();

        HouseholdDto householdDto = householdService.selectById(id);
        householdDto.setHouseholdRoomDtoList(householdRoomService.selectByHouseholdId(householdDto.getId()));

        return Response.<HouseholdDto>ok().wrap(householdDto);
    }


    @GetMapping("list")
    @Operation(summary = "查询住户列表")
    public Response<Page<HouseholdResp>> list(
            @Parameter(description = "网格id") @RequestParam(required = false) Long gridId,
            @Parameter(description = "住户姓名") @RequestParam(required = false) String householdName,
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize) {
        LoginGridMemberSession loginGridUserSession = SessionHolder.getLoginGridUserSession();
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        GridMemberDto gridMember = loginGridUserSession.getGridMember();

        List<Long> sourceIds = new ArrayList<>();
        // 精准网格
        if (gridId != null) {
            sourceIds = gridMemberBindResourcesBusiness.getSourceIdByGridIdAndSourceType(gridId, GridConstant.SourceType.BUILDING.getType());
        } else {
            sourceIds = gridMemberBindResourcesBusiness.getSourceIdByMemberIdAndSourceType(gridMember.getId(), GridConstant.SourceType.BUILDING.getType());
        }
        request.getParams().put(HouseholdConstants.BUILDING_IDS, sourceIds);
        request.put(LambdaUtil.getFieldName(HouseholdDto::getName), householdName);
        int total = householdService.queryTotal(request.getParams());
        List<HouseholdDto> list = null;
        List<HouseholdResp> recordList = new ArrayList<>();
        if (total > 0) {
            list = householdService.queryList(request.getParams());
            for (HouseholdDto householdDto : list) {
                householdDto.setMobile(DesensitizedUtil.mobilePhone(householdDto.getMobile()));
                householdDto.setCardNo(DesensitizedUtil.idCardNum(householdDto.getCardNo(), 2, 2));
                householdDto.setHouseholdRoomDtoList(householdRoomService.selectByHouseholdId(householdDto.getId()));
                HouseholdResp householdResp = CopyUtils.copyObj(householdDto, HouseholdResp.class);
                householdResp.setGridName(householdResp.getHouseholdRoomDtoList().get(0).getGridName());
                recordList.add(householdResp);
            }
        } else {
            list = new ArrayList<>();
        }

        Page<HouseholdResp> page = new Page<>(request.getPageNo(), request.getPageSize(), total, recordList);
        return Response.<Page<HouseholdResp>>ok().wrap(page);
    }

    @GetMapping("specialList")
    @Operation(summary = "查询住户列表")
    public Response<Page<HouseholdResp>> specialList(
            @Parameter(description = "人员特征,用逗号隔开,字典值HouseholdTag,示例't1,t2,t3'") @RequestParam(required = false) String searchKeysString,
            @Parameter(description = "网格id") @RequestParam(required = false) Long gridId,
            @Parameter(description = "住户姓名") @RequestParam(required = false) String householdName,
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize) {
        LoginGridMemberSession loginGridUserSession = SessionHolder.getLoginGridUserSession();
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));
        //人员特征筛选
        if (StringUtils.isNotBlank(searchKeysString)) {
            request.put(HouseholdConstants.TAG_KEYS, ListUtil.toList(request.getString(HouseholdConstants.SEARCH_KEYS_STRING).split(",")));
        }

        //添加重点人员筛选
        request.put(HouseholdConstants.FOCUS_GROUPS_FLAG, SystemConstants.YES);

        GridMemberDto gridMember = loginGridUserSession.getGridMember();

        List<Long> sourceIds = new ArrayList<>();
        // 精准网格
        if (gridId != null) {
            sourceIds = gridMemberBindResourcesBusiness.getSourceIdByGridIdAndSourceType(gridId, GridConstant.SourceType.BUILDING.getType());
        } else {
            sourceIds = gridMemberBindResourcesBusiness.getSourceIdByMemberIdAndSourceType(gridMember.getId(), GridConstant.SourceType.BUILDING.getType());
        }
        request.getParams().put(HouseholdConstants.BUILDING_IDS, sourceIds);
        request.put(LambdaUtil.getFieldName(HouseholdDto::getName), householdName);
        int total = householdService.queryTotal(request.getParams());
        List<HouseholdDto> list = null;
        List<HouseholdResp> recordList = new ArrayList<>();
        if (total > 0) {
            list = householdService.queryList(request.getParams());
            for (HouseholdDto householdDto : list) {
                householdDto.setMobile(DesensitizedUtil.mobilePhone(householdDto.getMobile()));
                householdDto.setCardNo(DesensitizedUtil.idCardNum(householdDto.getCardNo(), 2, 2));
                householdDto.setHouseholdRoomDtoList(householdRoomService.selectByHouseholdId(householdDto.getId()));
                HouseholdResp householdResp = CopyUtils.copyObj(householdDto, HouseholdResp.class);
                householdResp.setGridName(householdResp.getHouseholdRoomDtoList().get(0).getGridName());
                recordList.add(householdResp);
            }
        }

        Page<HouseholdResp> page = new Page<>(request.getPageNo(), request.getPageSize(), total, recordList);
        return Response.<Page<HouseholdResp>>ok().wrap(page);
    }

}